package com.example.administrator.application;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.widget.Toast;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.logging.Logger;

/**
 * @author Administrator
 */
public class ImageManager {
    private static ImageManager sInstance;
    private MediaScannerConnection mediaScannerConnection;

    public static ImageManager get() {
        if(sInstance == null) {
            synchronized (ImageManager.class) {
                if(sInstance == null) {
                    sInstance = new ImageManager();
                }
            }
        }
        return sInstance;
    }

    /**
     * 压缩宽高比例
     *
     * @param stream
     * @param wid
     * @param hei
     */
    public Bitmap sizeCompress(InputStream stream, int wid, int hei) {
        BitmapFactory.Options options = null;
        try {
            options = new BitmapFactory.Options();
            /**
             * 只解析bitmap的宽和高，不加载到内存中
             */
            options.inJustDecodeBounds = true;
            byte[] bytes = readStream(stream);
            BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options);
            options.inSampleSize = getInSampleSize(wid, hei, options);
            options.inJustDecodeBounds = false;
            return BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 从inputStream中获取字节流 数组大小
     *
     */
    private static byte[] readStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        outStream.close();
        inStream.close();
        return outStream.toByteArray();
    }

    /**
     * 质量压缩
     *
     * @param bitmap 位图文件
     * @param size 压缩后的大小如：100kb
     */
    public Bitmap qualityCompress(Bitmap bitmap, int size) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        int options = 100;
        bitmap.compress(Bitmap.CompressFormat.JPEG, options, bos);
        while (bos.toByteArray().length/1024 > size) {
            bos.reset();
            bitmap.compress(Bitmap.CompressFormat.JPEG, options, bos);
            options -= 10;
        }
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bos.toByteArray());
        return BitmapFactory.decodeStream(byteArrayInputStream);
    }

    /**
     * 获取实际的缩放比例
     */
    private int getInSampleSize(int w, int h, @NonNull BitmapFactory.Options options) {
        int inSampleSize = 1;
        if(options.outWidth > w || options.outHeight > h) {
            int widthScale = Math.round(options.outWidth/w);
            int heightScale = Math.round(options.outHeight/h);
            inSampleSize = Math.min(widthScale, heightScale);
        }
        return inSampleSize;
    }

    /**
     * 下载图片
     *
     * @param url
     * @param path
     */
    @SuppressLint("StaticFieldLeak")
    public void downLoadImage(String url, final String path) {
        new AsyncTask<String, Void, String>() {

            @Override
            protected String doInBackground(String... strings) {
                String u = strings[0];
                String p = strings[1];
                try {
                    if(!TextUtils.isEmpty(u) && !TextUtils.isEmpty(p)) {
                        URL uri = new URL(u);
                        HttpURLConnection connection = (HttpURLConnection) uri.openConnection();
                        connection.setConnectTimeout(10000);
                        connection.setDoInput(true);
                        InputStream inputStream = connection.getInputStream();
                        if(inputStream != null) {
                            File file = new File(p);
                            if(!file.getParentFile().exists()) {
                                file.getParentFile().mkdirs();
                            }
                            if(!file.exists()) {
                                file.createNewFile();
                            }
                            FileOutputStream outputStream = new FileOutputStream(file);
                            int len;
                            byte[] data = new byte[1024];
                            while ((len = inputStream.read(data)) != -1) {
                                outputStream.write(data, 0, len);
                            }
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return p;
            }

            @Override
            protected void onPostExecute(String path) {
                super.onPostExecute(path);
                insertImage(App.Companion.get().getApplicationContext(), path);
                Toast.makeText(App.Companion.get(), "图片下载成功", Toast.LENGTH_SHORT).show();
            }
        }.execute(url, path);
    }

    /**
     * 图片插入MediaProvider,通知图库更新
     *
     * @param context    context
     * @param filePath   文件路径
     */
    private String insertImage(Context context, final String filePath) {
        String result = null;

        try {
            result = MediaStore.Images.Media.insertImage(context.getContentResolver(), filePath, "test", null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // 通知图库更新
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri uri = Uri.fromFile(new File(filePath));
        intent.setData(uri);
        context.sendBroadcast(intent);

        mediaScannerConnection = new MediaScannerConnection(context, new MediaScannerConnection.MediaScannerConnectionClient() {
            @Override
            public void onMediaScannerConnected() {
                mediaScannerConnection.scanFile(filePath, "image/*");
            }

            @Override
            public void onScanCompleted(String path, Uri uri) {
                mediaScannerConnection.disconnect();
            }
        });
        mediaScannerConnection.connect();

        return result;
    }
}
